//
//  OffsetModifier.swift
//  ChinaPoem-Swift
//
//  Created by ming on 2025/2/16.
//

import SwiftUI

struct OffsetModifier: ViewModifier {
    @Binding var offset: CGFloat
    let coordinateSpace: String
    
    func body(content: Content) -> some View {
        content
            .background {
                GeometryReader { proxy in
                    Color.clear.preference(key: OffsetPreferenceKey.self, value: proxy.frame(in: .named(coordinateSpace)).minY)
                }
            }
            .onPreferenceChange(OffsetPreferenceKey.self) { prefer in
                if prefer < 0 {
                    offset = abs(prefer)
                    // print(prefer)
                }
            }
    }
}

struct OffsetPreferenceKey: PreferenceKey {
    typealias Value = CGFloat
    static var defaultValue: CGFloat = 0
    static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) { }
}

extension View {
    func trackScroll(value: Binding<CGFloat>, coordinateSpace: String) -> some View {
        self.modifier(OffsetModifier(offset: value, coordinateSpace: coordinateSpace))
    }
}
